import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../core/controllers/base_controller.dart';
import '../../../../core/controllers/global_controller.dart';
import '../../../../core/storage/storage_service.dart';

class SettingsController extends BaseController {
  final GlobalController _globalController = GlobalController.instance;
  final StorageService _storageService = StorageService.instance;

  // 观察属性
  final isDarkMode = false.obs;
  final currentLanguage = '中文'.obs;
  final pushNotificationEnabled = true.obs;
  final vibrationEnabled = true.obs;
  final soundEnabled = true.obs;
  final biometricEnabled = false.obs;
  final autoLockTime = '5分钟'.obs;
  final analyticsEnabled = true.obs;
  final cacheSize = '0 MB'.obs;
  final appVersion = '1.0.0'.obs;
  
  // 调试信息
  String get flutterVersion => '3.x.x';
  String get platform => 'Web/Mobile';
  String get deviceInfo => 'Flutter Application';

  @override
  void onInit() {
    super.onInit();
    setTitle('设置');
    loadSettings();
  }

  // 加载设置
  Future<void> loadSettings() async {
    await performAsyncOperation(() async {
      // 加载主题设置
      isDarkMode.value = _globalController.isDarkMode;
      
      // 加载语言设置
      final locale = _globalController.locale;
      currentLanguage.value = locale.languageCode == 'zh' ? '中文' : 'English';
      
      // 加载其他设置
      pushNotificationEnabled.value = _storageService.getUserPreference('push_notification', true) ?? true;
      vibrationEnabled.value = _storageService.getUserPreference('vibration', true) ?? true;
      soundEnabled.value = _storageService.getUserPreference('sound', true) ?? true;
      biometricEnabled.value = _storageService.getUserPreference('biometric', false) ?? false;
      analyticsEnabled.value = _storageService.getUserPreference('analytics', true) ?? true;
      
      // 计算缓存大小
      await calculateCacheSize();
      
      // 获取应用版本
      appVersion.value = _globalController.appVersion;
    });
  }

  // 切换暗黑模式
  Future<void> toggleDarkMode() async {
    await _globalController.toggleTheme();
    isDarkMode.value = _globalController.isDarkMode;
  }

  // 显示主题颜色选择器
  void showThemeColorPicker() {
    showInfoMessage('主题颜色选择功能');
  }

  // 显示语言选择器
  void showLanguagePicker() {
    Get.bottomSheet(
      Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('选择语言', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            const SizedBox(height: 20),
            ListTile(
              title: const Text('中文'),
              onTap: () => _setLanguage('zh', 'CN', '中文'),
            ),
            ListTile(
              title: const Text('English'),
              onTap: () => _setLanguage('en', 'US', 'English'),
            ),
          ],
        ),
      ),
    );
  }

  // 设置语言
  Future<void> _setLanguage(String languageCode, String countryCode, String displayName) async {
    await _globalController.setLocale(Locale(languageCode, countryCode));
    currentLanguage.value = displayName;
    Get.back();
  }

  // 切换推送通知
  Future<void> togglePushNotification() async {
    pushNotificationEnabled.value = !pushNotificationEnabled.value;
    await _storageService.setUserPreference('push_notification', pushNotificationEnabled.value);
  }

  // 切换震动
  Future<void> toggleVibration() async {
    vibrationEnabled.value = !vibrationEnabled.value;
    await _storageService.setUserPreference('vibration', vibrationEnabled.value);
  }

  // 切换声音
  Future<void> toggleSound() async {
    soundEnabled.value = !soundEnabled.value;
    await _storageService.setUserPreference('sound', soundEnabled.value);
  }

  // 切换生物识别
  Future<void> toggleBiometric() async {
    biometricEnabled.value = !biometricEnabled.value;
    await _storageService.setUserPreference('biometric', biometricEnabled.value);
  }

  // 显示自动锁定时间选择器
  void showAutoLockPicker() {
    showInfoMessage('自动锁定时间设置功能');
  }

  // 切换数据分析
  Future<void> toggleAnalytics() async {
    analyticsEnabled.value = !analyticsEnabled.value;
    await _storageService.setUserPreference('analytics', analyticsEnabled.value);
  }

  // 计算缓存大小
  Future<void> calculateCacheSize() async {
    try {
      // 这里可以计算实际的缓存大小
      cacheSize.value = '15.2 MB';
    } catch (e) {
      cacheSize.value = '0 MB';
    }
  }

  // 清除缓存
  Future<void> clearCache() async {
    final confirmed = await showConfirmDialog(
      title: '清除缓存',
      message: '确定要清除所有缓存数据吗？',
      confirmText: '清除',
      cancelText: '取消',
    );

    if (confirmed) {
      showLoadingDialog(message: '正在清除缓存...');
      
      try {
        await _storageService.clearCache();
        await calculateCacheSize();
        hideLoadingDialog();
        showSuccessMessage('缓存清除成功');
      } catch (e) {
        hideLoadingDialog();
        showErrorMessage('缓存清除失败: $e');
      }
    }
  }

  // 打开下载设置
  void openDownloadSettings() {
    showInfoMessage('下载设置功能');
  }

  // 打开备份设置
  void openBackupSettings() {
    showInfoMessage('备份与恢复功能');
  }

  // 打开关于页面
  void openAbout() {
    toNamed('/about');
  }

  // 打开意见反馈
  void openFeedback() {
    showInfoMessage('意见反馈功能');
  }

  // 检查更新
  Future<void> checkUpdate() async {
    showLoadingDialog(message: '正在检查更新...');
    
    try {
      await Future.delayed(const Duration(seconds: 2));
      hideLoadingDialog();
      showInfoMessage('当前已是最新版本');
    } catch (e) {
      hideLoadingDialog();
      showErrorMessage('检查更新失败: $e');
    }
  }

  // 重置设置
  Future<void> resetSettings() async {
    final confirmed = await showConfirmDialog(
      title: '重置设置',
      message: '确定要重置所有设置到默认值吗？',
      confirmText: '重置',
      cancelText: '取消',
    );

    if (confirmed) {
      showLoadingDialog(message: '正在重置设置...');
      
      try {
        await _globalController.resetUserPreferences();
        await loadSettings();
        hideLoadingDialog();
        showSuccessMessage('设置重置成功');
      } catch (e) {
        hideLoadingDialog();
        showErrorMessage('设置重置失败: $e');
      }
    }
  }
}